<?php

namespace App\Models;

use App\Events\Company\CreatedEvent;
use Illuminate\Support\Facades\Redis;
use Illuminate\Database\Eloquent\Model;
use App\Traits\Relation\CompanyRelation;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * 企业信息数据模型
 *
 * Date: 19/03/2018
 * @author George
 * @package App\Models
 */
class Company extends Model
{
	use SoftDeletes, CompanyRelation;

	/**
	 * 定义不可批量填充字段
	 *
	 * @var array
	 * Date: 23/03/2018
	 * @author George
	 */
	protected $guarded = ['id'];

	/**
	 * 定义隐藏字段
	 *
	 * @var array
	 * Date: 25/03/2018
	 * @author George
	 */
	protected $hidden = [
		'created_at', 'updated_at'
	];

	/**
	 * 定义事件
	 *
	 * @var array
	 * Date: 23/03/2018
	 * @author George
	 */
	protected $dispatchesEvents = [
		'created' => CreatedEvent::class
	];

	/**
	 * 获取公司启用的模块
	 *
	 * Date: 29/04/2018
	 * @author George
	 * @return array
	 */
	public function getModulesAttribute()
	{
		// 查询缓存是否存在
		$result = Redis::connection('company')->hvals("companies:{$this->getKey()}:modules");

		if (! $result) {
			// 不存在则查询数据库并写入缓存
			$result = $this->modules()->get();
			foreach ($result as $module) {
				Redis::connection('company')->hset("companies:{$this->getKey()}:modules", $module->code, $module);
			}
		}
		//
		foreach ($result as $key => $item) {
			if (is_string($item)) {
				$result[$key] = json_decode($item);
			}
		}

		return $result;
	}
}
